import os.path
import sys
from fastapi import FastAPI
from fastapi import  requests , responses
#from fastapi_offline import FastAPIOffline
import uvicorn
import os
from utils.componentManager import  componentManager

import utils.compIo
import utils.compDB
import utils.compWx
import utils.compRedis
import utils.compIotCalculate
#import utils.compDataBuffer

#app = FastAPIOffline()
app = FastAPI()
@app.get("/")
async def appRoot():
    return {
        'start app server 2025'
    }
@app.post("/znapi/{compCode}/{action}")
async def callPostApi( compCode:str , action:str , params:dict):
    res={
        "router":"callPostApi",
        "compCode": compCode ,
        "action": action ,
        "params": params
    }
    res = componentManager.getComponentActionResult(compCode , action , params)
    print(res)
    return  res
@app.get("/znapi/{compCode}/{action}")
async def callGetApi( compCode:str , action:str ,req : requests.Request):
    params= req.query_params._dict
    res = componentManager.getComponentActionResult(compCode , action , params    )
    return  res


class TSysInfo:
    def __init__(self):
        self.mainFile=""
        self.rootPath = ""
        self.params={}
    def update(self ,argvs = sys.argv):
        try:
            self.mainFile = argvs[0]
            self.rootPath = os.path.dirname(self.mainFile)
            self.params={}
            ind = 1
            while ind< len(argvs):
                curArgv = argvs[ind]
                if curArgv[0]=='-':
                    v = ''
                    if ind+1< len(argvs) and argvs[ind+1][0]!='-':
                        v = argvs[ind+1]
                    self.params[curArgv[1:]] = v
                ind = ind+1
        except Exception as er:
            print()

if __name__=="__main__":
    print('start server 2025...')
    settingsFileName = os.path.dirname(__file__)+"/defaultSettings.txt"
    sysInfo = TSysInfo()
    sysInfo.update(sys.argv)
    if 'c' in sysInfo.params.keys():
        seFn = sysInfo.params['c']
        exFlag = os.path.exists(seFn)
        if exFlag :
            settingsFileName = seFn
        else:
            print(f'settings file[{seFn}] is not exists')
    print( f'setting file: {settingsFileName}')
    componentManager.rootPath = os.path.dirname(__file__)
    componentManager.loadSettings(settingsFileName)
    print(f'start path:{componentManager.rootPath}')

    apiPort = componentManager.settings['server']['port']
    apiHost = componentManager.settings['server']['host']
    if 'p' in sysInfo.params.keys():
        try:
            apiPort = int( sysInfo.params['p'])
        except Exception as er:
            print(er)

    #from  utils.wx import  start, calPts ,wxStation
    #wxStation(componentManager)

    uvicorn.run(
        "server:app" ,
        host=apiHost,
        port=apiPort ,
        #reload= True
    )